package com.loren.demo13.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loren.demo13.data.entity.A;
import com.loren.demo13.data.entity.Article;
import com.loren.demo13.data.form.ArticleForm;
import com.loren.demo13.mapper.ArticleMapper;
import com.loren.demo13.utils.MPage;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
public class ArticleService {

    private final ArticleMapper articleMapper;

    @Transactional(readOnly = true)
    public MPage<Article> getArticleList(Integer page, Integer size) {
        Page<Article> pageInfo = Page.of(page, size);
        Page<Article> articleList = this.articleMapper.selectPage(pageInfo, Wrappers.<Article>lambdaQuery().eq(Article::getId, 1L));
        return new MPage<>(articleList);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getArticleList() {
        return this.articleMapper.selectAll();
    }

    @Transactional
    public void saveArticle(ArticleForm form) {
        Article article = new Article();
        BeanUtils.copyProperties(form, article);
        this.articleMapper.insert(article);
    }

    @Transactional
    public void updateArticle(Long articleId, ArticleForm form) {
        Article article = this.articleMapper.selectById(articleId);
        if (article == null) {
            throw new RuntimeException("找不到文章信息：" + articleId);
        }
        BeanUtils.copyProperties(form, article);
        article.setUpdateTime(null);
        this.articleMapper.updateById(article);
    }
}
